import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // 网页头部进度条
import 'nprogress/nprogress.css' // 网页头部进度条style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start 网页头部进度条
  NProgress.start()

  // 设置网页标题
  document.title = getPageTitle(to.meta.title)

  const hasToken =   getToken()
  if (hasToken) {
      
    if (to.path === '/login') {
      // 如果已经登录，重定向到首页
      next({ path: '/' })
      NProgress.done()
    } else {
        console.log('hasGetUserInfo',store.getters.name)
    //   const hasGetUserInfo = store.getters.name
      const hasGetUserInfo = ""
      if (hasGetUserInfo) {
            next()
      } else {
        try {
            console.log('获取用户信息')
          // get user info
        //   await store.dispatch('user/getInfo')

          next()
        } catch (error) {
            console.log('获取用户信息报错')
          // 删除token并定向到login重新登录 
        //   await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* 没有token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // 关闭 网页头部进度条
  NProgress.done()
})
